package com.estore.service;

import com.estore.model.Product;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


 //商品服务类，负责商品相关的业务逻辑
public class ProductService {

    // 使用Map存储商品数据，key是商品ID，value是商品对象
    // 优点：通过ID查找商品时，时间复杂度是O(1)，非常高效
    private final Map<String, Product> productData = new HashMap<>();

    //构造函数，初始化一些商品数据

    public ProductService() {
        initializeSampleData();
    }


     //初始化示例商品数据

    private void initializeSampleData() {
        productData.put("p001", new Product("p001", "Java从入门到精通", 99.0, 100));
        productData.put("p002", new Product("p002", "高性能MySQL", 128.5, 50));
        productData.put("p003", new Product("p003", "颈椎康复指南", 45.0, 200));
        productData.put("p004", new Product("p004", "生发秘籍", 88.0, 0)); // 库存为0的商品
        productData.put("p005", new Product("p005", "Spring Boot实战", 79.0, 75));
    }


     //获取所有商品列表

    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }


     // 根据ID查找商品
    public Product findProductById(String id) {
        if (id == null || id.trim().isEmpty()) {
            return null;
        }
        return productData.get(id.trim());
    }


     //添加新商品

    public boolean addProduct(Product product) {
        if (product == null || product.getId() == null || product.getId().trim().isEmpty()) {
            return false;
        }

        String id = product.getId().trim();
        if (productData.containsKey(id)) {
            return false; // 商品ID已存在
        }

        productData.put(id, product);
        return true;
    }


     //更新商品信息

    public boolean updateProduct(Product product) {
        if (product == null || product.getId() == null || product.getId().trim().isEmpty()) {
            return false;
        }

        String id = product.getId().trim();
        if (!productData.containsKey(id)) {
            return false; // 商品不存在
        }

        productData.put(id, product);
        return true;
    }


     //删除商品

    public boolean deleteProduct(String id) {
        if (id == null || id.trim().isEmpty()) {
            return false;
        }

        return productData.remove(id.trim()) != null;
    }


     //检查商品是否存在

    public boolean exists(String id) {
        if (id == null || id.trim().isEmpty()) {
            return false;
        }
        return productData.containsKey(id.trim());
    }

    //获取有库存的商品列表

    public List<Product> getAvailableProducts() {
        return productData.values().stream()
                .filter(product -> product.getStock() > 0)
                .collect(Collectors.toList());
    }


     //根据商品名称关键词搜索商品

    public List<Product> searchProductsByName(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return new ArrayList<>();
        }

        String searchTerm = keyword.trim().toLowerCase();
        return productData.values().stream()
                .filter(product -> product.getName().toLowerCase().contains(searchTerm))
                .collect(Collectors.toList());
    }


     //根据价格范围搜索商品

    public List<Product> searchProductsByPriceRange(double minPrice, double maxPrice) {
        if (minPrice < 0 || maxPrice < 0 || minPrice > maxPrice) {
            return new ArrayList<>();
        }

        return productData.values().stream()
                .filter(product -> product.getPrice() >= minPrice && product.getPrice() <= maxPrice)
                .collect(Collectors.toList());
    }


    //更新商品库存

    public boolean updateProductStock(String id, int newStock) {
        if (newStock < 0) {
            return false;
        }

        Product product = findProductById(id);
        if (product == null) {
            return false;
        }

        product.setStock(newStock);
        return true;
    }


     //减少商品库存

    public boolean decreaseProductStock(String id, int quantity) {
        if (quantity <= 0) {
            return false;
        }

        Product product = findProductById(id);
        if (product == null || product.getStock() < quantity) {
            return false;
        }

        product.setStock(product.getStock() - quantity);
        return true;
    }


    //增加商品库存

    public boolean increaseProductStock(String id, int quantity) {
        if (quantity <= 0) {
            return false;
        }

        Product product = findProductById(id);
        if (product == null) {
            return false;
        }

        product.setStock(product.getStock() + quantity);
        return true;
    }


     //获取所有商品数量

    public int getProductCount() {
        return productData.size();
    }


     //清空所有商品数据（主要用于测试）

    public void clearAllProducts() {
        productData.clear();
    }


     //批量添加商品

    public int addProducts(Collection<Product> products) {
        if (products == null || products.isEmpty()) {
            return 0;
        }

        int count = 0;
        for (Product product : products) {
            if (addProduct(product)) {
                count++;
            }
        }
        return count;
    }
}